package com.boomsecret.juc.locks;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author wangjinliang on 2019/1/18.
 */
public class ReentrantLockDemo {
    private static ReentrantLock reentrantLock = new ReentrantLock();
    private static final int THREAD_COUNT = 5;
    private volatile static int count = 0;

    public static void main(String[] args) throws Exception {
        Thread[] threads = new Thread[THREAD_COUNT];
        for (int index = 0; index < THREAD_COUNT; index ++) {
            threads[index] = new Thread(() -> {
                for (int count = 0; count < 2000; count ++) {
                    incrementAndGet();
                }
            });
            threads[index].start();
        }

        for (Thread thread : threads) {
            thread.join();
        }
        System.out.println(count);
    }

    public static void incrementAndGet() {
        reentrantLock.lock();
        try {
            count ++;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            reentrantLock.unlock();
        }
    }
}